package com.yuandian.management.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuandian.api.management.entity.ConfResourceBlacklist;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.enums.BlackListType;
import com.yuandian.management.service.ConfResourceBlacklistService;
import com.yuandian.management.service.ConfResourceFilterRuleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 迁移至 BPM3.0
 * agentip管理表-Service实现
 * @author zfsn
 * @date 2023-4-14
 */
@Service
@RequiredArgsConstructor
public class ConfResourceFilterRuleServiceImpl implements ConfResourceFilterRuleService {

	@Autowired
	private ConfResourceBlacklistService confResourceBlacklistService;


	/**
	 * 新增数据
	 * @param confResourceBlacklist 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public R<String> saveConfig(ConfResourceBlacklist confResourceBlacklist) {
		if (checkKeyDuplicates(confResourceBlacklist)){
			return R.failed("过滤字符串值重复,请修改");
		}

		String username = SecurityUtils.getUser().getName();
		confResourceBlacklist.setCreateBy(username);
		confResourceBlacklist.setCreateTime(LocalDateTime.now());
		confResourceBlacklist.setUpdateBy(username);
		confResourceBlacklist.setUpdateTime(LocalDateTime.now());

		// 兼容 4.0 t_it_filter_rule表 改为 4.1 conf_resource_blacklist
		confResourceBlacklist.setType(BlackListType.RESOURCE_FILTER_TYPE);

		confResourceBlacklistService.save(confResourceBlacklist);
		return R.ok();
	}

	/**
	 * 通过主键更新数据
	 *
	 * @param confResourceBlacklist 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R<String> updateById(ConfResourceBlacklist confResourceBlacklist) {
		if (checkKeyDuplicates(confResourceBlacklist)){
			return R.failed("过滤字符串值重复,请修改");
		}
		confResourceBlacklist.setUpdateBy(SecurityUtils.getUser().getName());
		confResourceBlacklist.setUpdateTime(LocalDateTime.now());

		// 兼容 4.0 t_it_filter_rule表 改为 4.1 conf_resource_blacklist
		confResourceBlacklist.setType(BlackListType.RESOURCE_FILTER_TYPE);

		confResourceBlacklistService.updateById(confResourceBlacklist);
		return R.ok();
	}

	/**
	 * 判断key 是否重复
	 * @param confResourceBlacklist
	 * @return
	 */
	private boolean checkKeyDuplicates(ConfResourceBlacklist confResourceBlacklist){
		LambdaQueryWrapper<ConfResourceBlacklist> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(ConfResourceBlacklist::getType, BlackListType.RESOURCE_FILTER_TYPE);
		queryWrapper.eq(ConfResourceBlacklist::getKey, confResourceBlacklist.getKey());
		if (confResourceBlacklist.getId() != null){
			queryWrapper.ne(ConfResourceBlacklist::getId, confResourceBlacklist.getId());
		}
		return confResourceBlacklistService.count(queryWrapper) > 0;
	}
}
